package com.cn.sys.main.service.impl;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import com.cn.sys.common.Constants;
import com.cn.sys.frame.dao.BaseSpringJdbcDao;
import com.cn.sys.frame.exception.ServiceException;
import com.cn.sys.frame.service.impl.BaseServiceImpl;
import com.cn.sys.frame.util.page.PageData;
import com.cn.sys.frame.util.query.QueryBean;
import com.cn.sys.frame.util.query.QueryCondition;
import com.cn.sys.main.annotation.OperationDescription;
import com.cn.sys.main.dao.SysUserDao;
import com.cn.sys.main.dao.SysUserRoleDao;
import com.cn.sys.main.entity.SysUser;
import com.cn.sys.main.entity.SysUserRole;
import com.cn.sys.main.service.SysUserService;

@Service("sysUserService")
public class SysUserServiceImpl extends BaseServiceImpl<SysUser, Long> implements
		SysUserService {

	private SysUserDao sysUserDao;
	@Autowired
	private SysUserRoleDao sysUserRoleDao;
	
	@Autowired
	public void setBaseDao(BaseSpringJdbcDao<SysUser, Long> sysUserDao) {
		this.baseDao = sysUserDao;
		this.sysUserDao = (SysUserDao) sysUserDao;
	}
	@Cacheable(value="sysUserCache", key = "#id + 'get'")
	public SysUser get(Long id) throws Exception {
		return super.get(id);
	}

	@OperationDescription(operateType = "save", 
	content = "添加用户信息\nID:${#user.id}\n用户名:${#user.userName}\n姓名:${#user.name}\n状态:${#user.status}\n电话:${#user.phone}\n创建时间:${#user.createTime}", 
	operateObj = "SysUser")
	public SysUser save(SysUser user) throws Exception {
		return super.save(user);
	}

	@OperationDescription(operateType = "update", 
	content = "修改用户信息\nID:${#user.id}\n用户名:${#user.userName}\n姓名:${#user.name}\n状态:${#user.status}\n电话:${#user.phone}\n更新时间:${#user.updateTime}", 
	operateObj = "SysUser")
	@CacheEvict(value="sysUserCache", key=" #user.id + 'get'")
	public SysUser update(SysUser user) throws Exception {
		return super.update(user);
	}

	@Override
	public long getCount(QueryCondition queryCondition) throws Exception {
		return super.getCount(queryCondition);
	}

	@Override
	public List<SysUser> getAll() throws Exception {
		return super.getAll();
	}

	public PageData<SysUser> getPageData(PageData<SysUser> pageData,
			QueryCondition queryCondition) throws Exception {
		String sql = "SELECT T1.*,T2.NAME ORGAN_NAME FROM SYS_USER T1 LEFT JOIN SYS_ORGAN T2 ON T1.ORGAN_ID=T2.ID WHERE 1=1";
		return sysUserDao.getPageData(pageData, sql, queryCondition);
	}

	public PageData<Map<String, Object>> getPageMapData(PageData<Map<String, Object>> pageData,
			QueryCondition queryCondition) throws Exception {
		String sql = "SELECT T1.*,T2.NAME \"ORGAN_NAME\" FROM SYS_USER T1 LEFT JOIN SYS_ORGAN T2 ON T1.ORGAN_ID=T2.ID WHERE 1=1";
		return sysUserDao.getPageMapData( pageData, sql, queryCondition);
	}

	public SysUser getByUserName(String userName) throws Exception{
		QueryBean qb = new QueryBean(" AND USER_NAME = ?", "USER_NAME", userName);
		QueryCondition queryCondition = new QueryCondition();
		queryCondition.setQueryBean(qb);
		return sysUserDao.get(queryCondition);
	}

	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class, readOnly=false)
	@OperationDescription(operateType = "delete", content = "删除用户信息\nID: ${#id}", operateObj = "SysUser")
	@CacheEvict(value="sysUserCache", key=" #id + 'get'")
	public int delete(Long id) throws Exception {
		QueryCondition queryCondition = new QueryCondition();
		QueryBean qb = new QueryBean(" WHERE USER_ID = ? ", "USER_ID", id);
		queryCondition.setQueryBean(qb);
		int result = 0;
		try {
			sysUserRoleDao.delete(queryCondition);
			queryCondition = new QueryCondition();
			qb = new QueryBean(" WHERE ID = ? ", "ID", id);
			queryCondition.setQueryBean(qb);
			qb = new QueryBean(" AND USER_NAME <> ? ", "USER_NAME", "system");
			queryCondition.setQueryBean(qb);
			result = sysUserDao.delete(queryCondition);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("删除用户失败! ["+e.getMessage()+"]");
		}
		return result;
	}

	@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class, readOnly=false)
	@OperationDescription(operateType = "assignRoleSave", content = "用户授权信息\n 用户ID:${#userId}\n 角色ID: ${#roleIds}", operateObj = "SysUser")
	public boolean assignRoleSave(String userId, String roleIds) throws Exception{
		QueryCondition queryCondition = new QueryCondition();
		QueryBean queryBean = new QueryBean("WHERE USER_ID = ?", "USER_ID", Long.valueOf(userId));
		queryCondition.setQueryBean(queryBean);
		String[] strArr = StringUtils.split(roleIds, ",");
		List<SysUserRole> list = new LinkedList<SysUserRole>();
		for (int i=0,len=strArr.length; i<len; i++) {
			if(StringUtils.isNotBlank(strArr[i])){
				SysUserRole userRole = new SysUserRole();
				userRole.setUserId(Long.valueOf(userId));
				userRole.setRoleId(Long.valueOf(strArr[i]));
				list.add(userRole);
			}
		}
		boolean result = true;
		try {
			sysUserRoleDao.delete(queryCondition);
			if(list!=null && !list.isEmpty()){
				sysUserRoleDao.batchSave(list);
			}
		} catch (Exception e) {
			result = false;
			e.printStackTrace();
			throw new ServiceException("用户授权失败! ["+e.getMessage()+"]");
		}
		return result;
	}
	
	@OperationDescription(operateType = "userLogin", content = "[${#user.userName}]用户登录,登录时间:${#user.loginTime},登录IP:${#user.loginIp}", operateObj = "SysUser")
	@CacheEvict(value="sysUserCache", key=" #user.id + 'get'")
	public void userLogin(SysUser user) throws Exception {
		sysUserDao.update(user);
	}
	@OperationDescription(operateType = "userLogout", content = "[${#user.userName}]用户退出,退出时间:${#user.logoutTime}", operateObj = "SysUser")
	@CacheEvict(value="sysUserCache", key=" #user.id + 'get'")
	public void userLogout(SysUser user) throws Exception {
		sysUserDao.getJdbcTemplate().update("UPDATE SYS_USER SET LOGOUT_TIME = ? WHERE ID = ?", user.getLogoutTime(), user.getId());
		//sysUserDao.update(user);
	}

	@OperationDescription(operateType = "initUserPwd", content = "用户ID[${#ids}]初始化密码", operateObj = "SysUser")
	public int initUserPwd(String ids) throws Exception {
		String[] strArr = ids.split(",");
		int result = 0;
		try {
			for (int i=0,len=strArr.length; i<len; i++) {
				String id = strArr[i];
				if(StringUtils.isNotBlank(id)&&StringUtils.isNumeric(id)){
					SysUser user = sysUserDao.get(Long.valueOf(id));
					user.setPassWord(DigestUtils.md5DigestAsHex(Constants.USER_INIT_PWD.getBytes()).toUpperCase());
					update(user);
					result ++;
				}
			}
		} catch (Exception e) {
			//e.printStackTrace();
			throw new ServiceException("初始化用户密码失败! ["+e.getMessage()+"]");
		}
		return result;
	}

	@OperationDescription(operateType = "changeUserPwd", content = "用户[${#user.userName}]修改密码", operateObj = "SysUser")
	@CacheEvict(value="sysUserCache", key=" #user.id + 'get'")
	public void changeUserPwd(SysUser user) throws Exception {
		sysUserDao.update(user);
	}
}
